package com.ruoyi.storage.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.storage.config.CosTenConfig;
import com.ruoyi.storage.config.OssAliConfig;
import com.ruoyi.storage.enums.BizTypeEnum;
import com.ruoyi.storage.model.dto.UploadFileDTO;
import com.ruoyi.storage.model.param.CosAuthInfoParam;
import com.ruoyi.storage.model.param.OssAuthInfoParam;
import com.ruoyi.storage.model.result.UploadFileResult;
import com.ruoyi.storage.service.ICosService;
import com.ruoyi.storage.service.IOssService;
import com.ruoyi.storage.service.IStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class StorageServiceImpl implements IStorageService {

    @Autowired
    OssAliConfig ossAliConfig;
    @Autowired
    IOssService ossService;

    @Autowired
    CosTenConfig cosTenConfig;
    @Autowired
    ICosService cosService;

    @Override
    public UploadFileResult uploadFileHandle(UploadFileDTO uploadFileDTO) throws Exception {

        UploadFileResult uploadFileResult = new UploadFileResult();
        uploadFileResult.setSuccess(false);

        BizTypeEnum entityByBizType = BizTypeEnum.getEntityByBizType(uploadFileDTO.getBizType());
        if (ObjectUtil.isEmpty(entityByBizType)){
            return uploadFileResult;
        }

        OssAuthInfoParam ossAuthInfoParam = new OssAuthInfoParam();
        if (ObjectUtil.equals(entityByBizType.getPriFlag(), Integer.valueOf(1))){
            ossAuthInfoParam.setRegionId(ossAliConfig.getPriRegionId());
            ossAuthInfoParam.setBucketName(ossAliConfig.getPriBucketName());
            ossAuthInfoParam.setEndpoint(ossAliConfig.getPriEndpoint());
            ossAuthInfoParam.setHostUrl(ossAliConfig.getPriHostUrl());
        }else{
            ossAuthInfoParam.setRegionId(ossAliConfig.getRegionId());
            ossAuthInfoParam.setBucketName(ossAliConfig.getBucketName());
            ossAuthInfoParam.setEndpoint(ossAliConfig.getEndpoint());
            ossAuthInfoParam.setHostUrl(ossAliConfig.getHostUrl());
        }

        String objectKey = this.getObjectKey(entityByBizType, uploadFileDTO.getOriginFileName());
        ossService.uploadFile(objectKey, uploadFileDTO.getInputStream(), ossAuthInfoParam);

        String fileUrl = ossAuthInfoParam.getHostUrl() + objectKey;
        uploadFileResult.setSuccess(true);
        uploadFileResult.setFileUrl(fileUrl);

        return uploadFileResult;

    }


    private String getObjectKey(BizTypeEnum entityByBizType, String originFileName){
        String fileName = RandomUtil.randomString(16);
        String substring = originFileName.substring(originFileName.lastIndexOf("."));
        fileName = fileName + substring;
        String objectKey = StrUtil.format(entityByBizType.getPath(), fileName);
        return objectKey;
    }
}
